<script setup lang="ts">
import { loginPasswordApi } from '@/apis/user';
import { useUserStore } from '@/stores/user';
import { ref } from 'vue';

  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })
    //表单数据
    const formData = ref({
    mobile:'13230000029',
    password:'abc12345'
  })
   // 表单组件 ref
   const form = ref<UniHelper.UniFormsInstance>()
    // 验证表单数据的规则
    const formRules: UniHelper.UniFormsRules = {
      mobile:{
        rules:[{required:true,errorMessage:'请输入手机号'},
               {pattern:'^1[0-9]{10}$',errorMessage:'请输入正确的手机号'}
        ]
      },
      code:{
        rules:[{required:true,errorMessage:'请输入密码'},
               {pattern:'^abc12345$',errorMessage:'请输入正确的密码'}
        ]
      }
    }
    const isAgree = ref(false)
       // 提交表单
  const onSubmit = async () => {
    try {
      // 校验表单所有字段
     await form.value?.validate?.()
    //  是否同意用户协议
    if(!isAgree.value){
      return uni.showToast({title: '请勾选用户协议',icon:'none'});
    }
      const res = await loginPasswordApi(formData.value)
       // console.log('登录成功', res.token)
      // 保存 token 到 store 中，store 已开启持久化
      const store = useUserStore()
      store.setToken(res.token)
      // 成功提示
      uni.showToast({ title: '登录成功', icon: 'success' })
      // 登录成功，跳转首页，注意：这里需要用 switchTab
      uni.switchTab({ url: '/pages/index/index' })
    } catch (error) {
      console.log(error)
    }
  }
</script>

<template>
  <uni-forms class="login-form" :model="formData" :rules="formRules" ref="form">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
        v-model="formData.password"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree=!isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button @click="onSubmit()" class="uni-button">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
